<?php
defined('_JEXEC') or die();

class WrdControllerProfile extends JControllerLegacy 
{
	protected $option;
	protected $controller;	
	
	function __construct( $default = array()){
		
		$this->option = 'com_wrd';
		$this->controller = 'profile';
		$this->layout = JRequest::getVar('layout') ;
		parent::__construct( $default );
	}
	
	function display()
	{
		switch($this->getTask()){
			case 'add':{
				JRequest::setVar( 'layout', 'form'  );
				JRequest::setVar( 'view'  , 'profile');
			} 
			break;
			default:
				JRequest::setVar( 'view'  , 'profile');
			break;
		}
		parent::display();
	}
	
    function save(){
		$post = JRequest::get('post');
		
		$checkSendEmailNotification = WrdHelper::sendEmailNoticeWhenChangeProfile($post,$post['id'],$fontEnd = false);
		
		$db = JFactory::getDbo();
		$query = 'SELECT number FROM #__wrd_lucky_num WHERE published = 1 and available = 1';
		$db->setQuery($query);
		$rows = $db->loadObjectList();
		$checkMemberRenew = 0;
		foreach($rows as $rs):
			if($rs->number == $post['member_id']) {$checkMemberRenew = 1 ;break; }
		endforeach;
		$memberRenew = WrdHelper::uRenewMemberId();
		if(isset($_POST['status_of_card']) && ($_POST['status_of_card'] == 2)){
			$post['non_pick_up_at'] = $post['non_mem_card_outlet'];
			$post['pick_up_at'] = $post['mem_card_outlet'];
		}
		else if(isset($_POST['status_of_card']) && ($_POST['status_of_card'] == 3)){
			$post['pick_up_at'] = $post['mem_card_outlet'];
			$post['non_pick_up_at'] = $post['non_mem_card_outlet'];
		}
	   	if(!empty($post['member_id'])){
			date_default_timezone_set('Asia/Ho_Chi_Minh'); 
			$sql = "UPDATE `#__wrd_lucky_num` SET `available` = '0' WHERE `#__wrd_lucky_num`.`number` =".$post['member_id'];
			$db = JFactory::getDbo();
			$db->setQuery($sql);
			$db->query();
			if(isset($post['password1'])){
				
				$post['password1'] = $post['member_id'].$post['year_birth'];
				$post['password2'] = $post['password1'];
				
			}
		   $post['u_name'] = $post['email1'];
		   $post['u_pass'] = $post['password1'];
		  
		   if($this->isEmail($post['email1'])){
		   }else{
				$post['email1'] = $post['email1'].'@wmcvip.vn' ;
		   }
		   
		   $post['project_id'] = '01' ;
		   $post['club_id'] = '01' ;
		   $post['f_name'] 			= ucwords(strtolower(trim($post['f_name'])));
		   $post['l_name'] 			= ucwords(strtolower(trim($post['l_name'])));
		   $post['name_on_card'] 	= ucwords(strtolower($post['name_on_card']));
		   
		   if($post['o_source']=='other' && isset($post['other_source'])){
		   	$source_db = JFactory::getDbo() ;
		   	$c_s_user = JFactory::getUser() ;
		   	$source_obj = new stdClass() ;
		   	$source_obj->id = null;
		   	$source_obj->name = $post['other_source'] ;
		   	$source_obj->des = $post['other_source'] ;
		   	$source_obj->published = 1 ;
		   	$source_obj->created_id = $c_s_user->id ;
		    $source_obj->created_date = date("Y-m-d") ;
		   	
			
			$source_db->insertObject('#__wrd_sources', $source_obj) ;
		   	$post['o_source'] = $source_db->insertid() ;
		   	unset($post['other_sources']);
		   	unset($source_db);
		   }
	       if(!isset($post['status_of_card'])){
	       		$post['status_of_card'] = 1 ;
	       }
		  
	       $post['status_of_card_date'] = date('Y-m-d H:i:s') ;
	       
	       unset($post['complain_flag'] ) ;
	       
	       	if(!empty($post['hobbies'])){
				$tmp_hb = array();
				foreach ($post['hobbies'] as $record){
					$tmp_hb[$record] = $record;
				}
				$tmp_hb = serialize($tmp_hb);
				$post['hobbies'] = $tmp_hb;
				unset($tmp_hb);
			}
			if(!empty($post['social'])){		
				$tmp = array();
				foreach ($post['social'] as $row){
					$tmp[$row] = $row;
				}
				$tmp = serialize($tmp);
				$post['social'] = $tmp;
				unset($tmp);
			}
	    	if(!empty($post['o_club']))
			{		
				$tmp1 = array();
				foreach ($post['o_club'] as $row){
					$tmp1[$row] = $row;
				}
				$tmp1 = serialize($tmp1);
				$post['o_club'] = $tmp1;
				unset($tmp1);
			}
	    	if(!empty($post['bation']))
			{		
				$tmp2 = array();
				foreach ($post['bation'] as $row){
					$tmp2[$row] = $row;
				}
				$tmp2 = serialize($tmp2);
				$post['bation'] = $tmp2;
				unset($tmp2);
			}
			
	        if(!empty($post['weekend_action']))
			{		
				$tmp_aw = array();
				foreach ($post['weekend_action'] as $row){
					$tmp_aw[$row] = $row;
				}
				$tmp_aw = serialize($tmp_aw);
				$post['weekend_action'] = $tmp_aw;
				unset($tmp_aw);
			}
	    	if(!empty($post['user_id'])){
				$post['modify_by'] = $post['created_id'] ;
				unset($post['created_id']) ;
			}
			$post['dob'] = "";
	    	if(isset($post['year_birth'])&& isset($post['month_birth']) && isset($post['day_birth'] )){
				$year_birth =  $post['year_birth'] ;
		    	$month_birth = $post['month_birth'] ;
				$day_birth = $post['day_birth'] ;
				$post['dob'] = 	"$year_birth-$month_birth-$day_birth" ;
				unset($post['year_birth']); unset($post['month_birth']); unset($post['day_birth']);
	        }
			if(!empty($post['user_id'])){
				unset($post['created_date']) ;
			}else{
	       		$post['created_date'] = date("Y-m-d H:i:s") ;
			}
			
			if(!empty($post['user_id'])){
		    	if(empty($post['non_pick_up_date'])){
					unset($post['non_pick_up_date']) ;
				}
			}else{
				$post['non_pick_up_date'] = '' ;
			} 
	    	if(!empty($post['user_id'])){
		    	if(empty($post['pick_up_date'])){
					unset($post['pick_up_date']) ;
				}
			}else{
				$post['pick_up_date'] = '' ;
			}
			
	       	$post['modify_date'] = date("Y-m-d H:i:s");
	       	$params = JComponentHelper::getParams('com_wrd');
			
			$model=$this->getModel('profile');
	       	$data = $model->register($post,0);
	       	
			if(($memberRenew == $post['member_id'])||($checkMemberRenew)):
				$q = "UPDATE `#__wrd_profile` SET renew = 'I' WHERE `#__wrd_profile`.`member_id` =".$post['member_id'];
				$db->setQuery($q);
				$db->query();
			endif;
			
			$profile =  WrdHelper::getUserProfile($post['member_id'],'member_id');
			WrdHelper::updatePointOfUser($profile->user_id,$profile->member_id,$profile->dob,$profile->f_name,$profile->l_name);
			//get date current
	       	if($data!=0){
	       		$this->setRedirect('index.php?option='.$this->option.'&controller='.$this->controller,'Saved.');
	       		return true;
	       	}else{
	       		$this->setRedirect('index.php?option='.$this->option.'&controller='.$this->controller,JError::getError());
	       		return false;
	       	}
	   }else{
       		$this->setRedirect('index.php?option='.$this->option.'&controller='.$this->controller,'Error, must have be a code');
       		return false;
       }
	   
	   
    }  
   	
    function apply(){
	   
		$post = JRequest::get('post');
	    // echo "<pre>";print_r($post);exit;
		$checkSendEmailNotification = WrdHelper::sendEmailNoticeWhenChangeProfile($post,$post['id'],$fontEnd = false);
		
		/*
		$MessageForSendEmailNotification = "";
		if($checkSendEmailNotification){
				
			$MessageForSendEmailNotification = ", Sent email notification when change fields on profile has sucessfully";
		}
		*/
		$db = JFactory::getDbo();
		$query = 'SELECT number FROM #__wrd_lucky_num WHERE published = 1 and available = 1';
		$db->setQuery($query);
		$rows = $db->loadObjectList();
		$checkMemberRenew = 0;
		foreach($rows as $rs):
			if($rs->number == $post['member_id']) {$checkMemberRenew = 1; break; }
		endforeach;
		$memberRenew = WrdHelper::uRenewMemberId();
	   if(!empty($post['member_id'])){
			$sql = "UPDATE `#__wrd_lucky_num` SET `available` = '0' WHERE `#__wrd_lucky_num`.`number` =".$post['member_id'];
			$db->setQuery($sql);
			$db->query();
			
			if (isset($post['password1'])){
			
				$post['password1'] = $post['member_id'].$post['year_birth'];
				$post['password2'] = $post['password1'];
			}
			$post['u_name'] = $post['email1'] ;
			$post['u_pass'] = $post['password1'];
			if(!$this->isEmail($post['email1'])){
				$post['email1'] = $post['email1'].'@wmcvip.vn' ;
			}
			
		   $post['project_id'] = '01' ;
		   $post['club_id'] = '01' ;
		   $post['f_name'] = ucwords(strtolower(trim($post['f_name'])));
		   $post['l_name'] = ucwords(strtolower(trim($post['l_name'])));
		   $post['name_on_card'] 	= ucwords(strtolower($post['name_on_card']));
		   if($post['o_source']=='other' && isset($post['other_source'])){
			   	$source_db = JFactory::getDbo() ;
			   	$c_s_user = JFactory::getUser() ;
			   	$source_obj = new stdClass() ;
			   	$source_obj->id = null;
			   	$source_obj->name = $post['other_source'] ;
			   	$source_obj->des = $post['other_source'] ;
			   	$source_obj->published = 1 ;
			   	$source_obj->created_id = $c_s_user->id ;
			   	$source_obj->created_date = date("Y-m-d") ;
			   	$source_db->insertObject('#__wrd_sources', $source_obj) ;
			   	$post['o_source'] = $source_db->insertid() ;
			   	unset($post['other_sources']);
			   	unset($source_db);
		   }
		   
	       //status_of_card_date
	       if(!isset($post['status_of_card'])){
	       		$post['status_of_card'] = 1 ;
	       }
	       $post['status_of_card_date'] = date('Y-m-d H:i:s') ;
	       
			if(!empty($post['hobbies'])){
				$tmp_hb = array();
				foreach ($post['hobbies'] as $record){
					$tmp_hb[$record] = $record;
				}
				$tmp_hb = serialize($tmp_hb);
				$post['hobbies'] = $tmp_hb;
				unset($tmp_hb);
			}
			if(!empty($post['social']))
			{		
				$tmp = array();
				foreach ($post['social'] as $row){
					$tmp[$row] = $row;
				}
				$tmp = serialize($tmp);
				$post['social'] = $tmp;
				unset($tmp);
			}
	        if(!empty($post['weekend_action']))
			{		
				$tmp_aw = array();
				foreach ($post['weekend_action'] as $row){
					$tmp_aw[$row] = $row;
				}
				$tmp_aw = serialize($tmp_aw);
				$post['weekend_action'] = $tmp_aw;
				unset($tmp_aw);
			}
	    	if(!empty($post['o_club']))
			{		
				$tmp1 = array();
				foreach ($post['o_club'] as $row){
					$tmp1[$row] = $row;
				}
				$tmp1 = serialize($tmp1);
				$post['o_club'] = $tmp1;
				unset($tmp1);
			}
	    	if(!empty($post['bation']))
			{		
				$tmp2 = array();
				foreach ($post['bation'] as $row){
					$tmp2[$row] = $row;
				}
				$tmp2 = serialize($tmp2);
				$post['bation'] = $tmp2;
				unset($tmp2);
			}
			
			$post['dob'] = "";
	    	if(!empty($post['year_birth'])&& !empty($post['month_birth']) && !empty($post['day_birth'] )){
			
				$year_birth =  $post['year_birth'] ;
		    	$month_birth = $post['month_birth'] ;
				$day_birth =   $post['day_birth'] ;
				$post['dob'] = 	"$year_birth-$month_birth-$day_birth" ;
				unset($post['year_birth']); unset($post['month_birth']); unset($post['day_birth']);
				
	        }
			
			if(!empty($post['user_id'])){
				unset($post['created_date']) ;
			}else{
	       		$post['created_date'] = date("Y-m-d H:i:s") ;
			}
			
			if(!empty($post['user_id'])){
		    	if(empty($post['pick_up_date'])){
					unset($post['pick_up_date']) ;
				}
			}else{
				$post['pick_up_date'] = '' ;
			}
	    	if(empty($post['member_id'])){
				unset($post['member_id']) ;
			}
		
			if(isset($post['status_of_card']) && ($post['status_of_card'] == 2)){
				$post['non_pick_up_at'] = $post['non_mem_card_outlet'];
				$post['pick_up_at'] = $post['mem_card_outlet'];
			}
			else if(isset($post['status_of_card']) && ($post['status_of_card'] == 3)){
				$post['pick_up_at'] = $post['mem_card_outlet'];
				$post['non_pick_up_at'] = $post['non_mem_card_outlet'];
			}
			$post['modify_date'] = date("Y-m-d H:i:s");
	       	$params = JComponentHelper::getParams('com_wrd');
	       	$model = $this->getModel('profile');
			
			//echo '<pre>';print_r($post);die;
			$data = $model->register($post,0);

			if(($memberRenew == $post['member_id'])||($checkMemberRenew)):
				$q = "UPDATE `#__wrd_profile` SET renew = 'I' WHERE `#__wrd_profile`.`member_id` =".$post['member_id'];
				$db->setQuery($q);
				$db->query();
			endif;
			$profile =  WrdHelper::getUserProfile($post['member_id'],'member_id');

			WrdHelper::updatePointOfUser($profile->user_id,$profile->member_id,$profile->dob,$profile->f_name,$profile->l_name);
			
			//get date current
	       	if(!empty($data)){
	       		if($post['tab'] != ''){
			   		switch ($post['tab']) {
			   			case 'create_account':
			   				$post['tab'] = 'card_registration_information';	
			   				break;
			   			case 'card_registration_information':
			   				$post['tab'] = 'commercial_infomation';
			   				break;
			   			case 'personal_information':
			   				$post['tab'] = 'create_account';
			   				break;
			   			case 'commercial_infomation':
			   				$post['tab'] = 'professionalism';
			   				break;
			   			case 'professionalism':
			   				$post['tab'] = 'status';
			   				break;
			   			default:
			   				$post['tab'] = 'create_account';
			   			break;
			   		}
					$post[id] == 0 ? $post[id] = $data: '';
	       			$this->setRedirect('index.php?option='.$this->option.'&controller='.$this->controller.'&id='.$post[id].'&layout=form&tab='.$post['tab'],'Saved.'.$MessageForSendEmailNotification);			
			   		return true;
	       		}else{
		       		$this->setRedirect( 'index.php?option='.$this->option.'&controller='.$this->controller.'&id='.$post['id'].'&layout=form','Saved.');
					return true;  
				}              
	       	}else{
	       		
				$this->setRedirect( 'index.php?option='.$this->option.'&controller='.$this->controller.'&layout=form','Error Saved.');
	            return false;
	       	}
	    }else{
			$this->setRedirect( 'index.php?option='.$this->option.'&controller='.$this->controller.'&layout=form','Error, must be have a code.');
            return false;
	    }
    }
	public function getPointCashProduct(){
		
		$id = JRequest::getInt("id");
		$mProduct	= &JModelLegacy::getInstance('products','WrdModel');
		$product = $mProduct->getItem($id);
		echo number_format($product->point,0,',',',').";".number_format($product->pointx,0,',',',').";".number_format($product->cash,0,',',',');
		jexit();
		
	}	
	public function resetPass(){
	
		$db = JFactory::getDbo();
		$post = JRequest::get('post');

	   if($post['member_id']){
	   
			$password = $post['member_id'].$post['year_birth'];
			$sql = 'UPDATE #__users SET password = MD5( "'.$password.'" ), block = 0 WHERE id ='. $post['user_id'];
			$db->setQuery($sql);
			$db->query();
			
			$db = JFactory::getDbo();
			$query = "SELECT username FROM #__users where id = ".$post['user_id'];
			$db->setQuery($query);
			$username = $db->loadObject();
			$rs_sendEmail = WrdHelper::sendEmailWhenStaffResetPassMember($post,$username->username);
			
			if($rs_sendEmail){
				
				if($post['p_email'] != ''){
					
					$message = "Reset password successful. Memeber ". $post['member_id']." can be login by username: ".$username->username." OR ".$post['p_email']." and pass: ". $password;
					$message .= ". Email template reset password sent to '".$post['p_email']."' sucessfully ";
					
				}
				else
				{
					
					$message = "Reset password successful. Memeber ". $post['member_id']." can be login by username: ".$username->username." and pass: ". $password;
					$message .= ". Email template reset password sent to '".$post['alternative_email']."' sucessfully ";
				}
				
				$this->setRedirect('index.php?option='.$this->option.'&controller='.$this->controller.'&id='.$post[id].'&layout=form&tab='.$post['tab'],$message);
			}
			else {
			
				$this->setRedirect('index.php?option='.$this->option.'&controller='.$this->controller.'&id='.$post[id].'&layout=form&tab='.$post['tab'],'Reset password successful.Member '.$post['member_id'].' can be login by username: '.$username->username.' or '.$post['p_email'].' and pass:'.$password." Sent email template reset password has failure");
			}
	   }
	   else 
			$this->setRedirect('index.php?option='.$this->option.'&controller='.$this->controller.'&id='.$post[id].'&layout=form&tab='.$post['tab'],'Error reset password');
	}
	//Use if new record in table #__wrd_point but not yet convert point to table #__wrd_points_summary
    public function convertToSummaryPoint(){
		//(created_date BETWEEN "'.date("Y-m").'-01" AND "'.date("Y-m").'-31")AND
		$db = JFactory::getDbo();
		$sql = 'SELECT id,user_id,created_date FROM #__wrd_point WHERE flagConvert=1';
		$db->setQuery($sql);
		$rows = $db->loadObjectList();
		
		if(count($rows)):foreach($rows as $row):	
			$day = date('d',strtotime($row->created_date));
			$month = date('m',strtotime($row->created_date));
			$year = date('Y',strtotime($row->created_date));
			
			if($day=='01'){
				$month=$month-1;
				if($month==0){$month=12;$year=$year-1;}
			}
			
			if($year < date('Y')||(($year == date('Y'))&&($month <= date('m')))){
				while(($month != date('m'))||($year != date('Y'))){
					WrdHelper::updateSummaryPoint($row->user_id,$year,$month);
					if($month+1 <=12) ++$month;
					else {$month = 1;++$year;}
				}
				WrdHelper::updateSummaryPoint($row->user_id,date('Y'),date('m'));
			}
			
			$p_o_u = WrdHelper::getPoints($row->user_id);
			$sql = 'UPDATE #__wrd_profile SET p_o_u = '.$p_o_u->point.', point_life_time = '.$p_o_u->point_life_time.' WHERE user_id = '.$row->user_id;
			$db->setQuery($sql);
			$db->query();
			
			$profile =  WrdHelper::getUserProfile($row->user_id,'userid');
			WrdHelper::updatePointOfUser($row->user_id,$profile->member_id,$profile->dob,$profile->f_name,$profile->l_name);
			
			$query = 'UPDATE #__wrd_point SET `flagConvert` = "0" WHERE id ='.$row->id;
       		$db->setQuery($query);
			$db->query();
		endforeach;endif;
			$this->setRedirect('index.php?option='.$this->option.'&controller='.$this->controller);
		return true;  
		
	}
	
	function convertTransactionToPoint($vipnumber){
		$db = JFactory::getDbo();
		$user = JFactory::getUser();
		$created_id = empty($user->id) ? '' : $user->id ;
		$sql = "DELETE FROM #__wrd_point WHERE (user_id = 0) OR (user_id = NULL)";
		$db->setQuery($sql);
		$db->query();
		$query = "SELECT id,food,outlet,beverage,other,netsale,discount,date_receipt FROM #__wrd_transaction WHERE `vip_number` = ".$vipnumber;
		$db->setQuery($query);
		$data = $db->loadObjectList();
		if(count($data) > 0){
			$moneyForOnePoint = PointProvider::getConfigByName($db, 'money_for_one_point');			
			$moneyForOnePoint = ($moneyForOnePoint > 0 ? $moneyForOnePoint : 50000);
			$defaultPointPerMoney  = PointProvider::getConfigByName($db, 'default_point_per_money');
			$defaultPointPerMoney = ($defaultPointPerMoney > 0 ? $defaultPointPerMoney : 100);
			foreach($data as $val=>$item){
				
				$point = WrdHelper::machPoint($item->id,'transaction');
				if($point->point == 0){
					$point->point = $defaultPointPerMoney;
				}
				
				if(($point->f==0)&&($point->b==0)&&($point->o==1)) 
					$p = intval(($item->other) / $moneyForOnePoint) * $point->point;
				else if(($point->f==0)&&($point->b==1)&&($point->o==0)) 
					$p = intval(($item->beverage) / $moneyForOnePoint) * $point->point;
				else if(($point->f==0)&&($point->b==1)&&($point->o==1)) 
					$p = intval(($item->beverage+$item->other) / $moneyForOnePoint) * $point->point;
				else if(($point->f==1)&&($point->b==0)&&($point->o==0)) 
					$p = intval($item->food / $moneyForOnePoint) * $point->point;
				else if(($point->f==1)&&($point->b==0)&&($point->o==1)) 
					$p = intval(($item->food+$item->other) / $moneyForOnePoint) * $point->point;
				else if(($point->f==1)&&($point->b==1)&&($point->o==0)) 
					$p = intval(($item->food+$item->beverage) / $moneyForOnePoint) * $point->point;
				else 
					$p = intval(($item->netsale) / $moneyForOnePoint) * $point->point;
				
				$expire  = WrdHelper::calculateExpiredDate($item->date_receipt);
				if($expire != '0000-00-00'){
					if(strtotime($expire.' 23:59:59') < time()) 
						$expired = 1;
					else $expired = 0;
				}
				else
					$expired = 0;
				
				$query = "SELECT count(id) as total FROM #__wrd_point WHERE user_id = ".$point->user_id ." AND `transaction` = ".$point->tran;
				$db->setQuery($query);
				$rs = $db->loadObject();
				if($rs->total==0):
					
					$obj = new stdClass;
					$obj->id = null;
					$obj->user_id = $point->user_id;
					$obj->outlet = $item->outlet;
					$obj->transaction = $point->tran;
					$obj->type = 'transaction';
					$obj->point = $p ;
					$obj->expire = $expire;
					$obj->expired = $expired;
					$obj->remain = $p;
					$obj->des = 'transaction';
					$obj->created_id = $created_id ;
					//$obj->created_date = date('Y-m-d') ;
					$obj->created_date = $item->date_receipt;
					$obj->modify_id = '' ;
					$obj->modify_date = '' ;
				
					$db->insertObject('#__wrd_point', $obj);
					// Update lai point summary cho user
					$month = date('m',strtotime($obj->created_date));
					$year = date('Y',strtotime($obj->created_date));
					if($year < date('Y')||(($year == date('Y'))&&($month <= date('m')))){
						while(($month != date('m'))||($year != date('Y'))){
							WrdHelper::updateSummaryPoint($obj->user_id,$year,$month);
							if($month+1 <=12) ++$month;
							else {$month = 1;++$year;}
						}
						WrdHelper::updateSummaryPoint($obj->user_id,date('Y'),date('m'));
					}
				endif;
			}
		}
	}
	//Danh cho truong hop point ko dong nhat sau khi import.
	//Show in detail profile 
	function uPoint(){
		$auto = JRequest::getInt('auto',0);
		if($auto == 1)
		{
			$id = JRequest::getVar('id');
			$post = (array)WrdHelper::getUserProfile($id,'id');
		}else{
			$post = JRequest::get('post');
		}
		
		$this->convertTransactionToPoint($post['member_id']);
		$year = 2013;$month = 01;
		
		if($year < date('Y')||(($year == date('Y'))&&($month <= date('m')))){
			while(($month != date('m'))||($year != date('Y'))){
				WrdHelper::updateSummaryPoint($post['user_id'],$year,$month);
				if($month+1 <=12) ++$month;
				else {$month = 1;++$year;}
			}
		}
		
		WrdHelper::updateSummaryPoint($post['user_id'],date('Y'),date('m'));
		$db = JFactory::getDbo();
		$p_o_u = WrdHelper::getPoints($post['user_id']);
		$sql = 'UPDATE #__wrd_profile SET p_o_u = '.intval($p_o_u->point) .' ,point_life_time = '.$p_o_u->point_life_time.' WHERE user_id = '.$post['user_id'];
		$db->setQuery($sql);
		$db->query();
		
		$dob = $post['year_birth']."-".$post['month_birth']."-".$post['day_birth'];
		WrdHelper::updatePointOfUser($post['user_id'],$post['member_id'],$dob,$post['f_name'],$post['l_name']);
		$this->setRedirect('index.php?option=com_wrd&controller=profile&id='.$post['id'].'&layout=form&tab=point','Finish update point');
	}
	
	function uSpend(){
		$post = JRequest::get('post');
		$year = 2013;$month = 01;
		if($year < date('Y')||(($year == date('Y'))&&($month <= date('m')))){
			while(($month != date('m'))||($year != date('Y'))){
				WrdHelper::uSummarySpend($post['member_id'],$year,$month);
				if($month+1 <=12) ++$month;
				else {$month = 1;++$year;}
			}
		}
		WrdHelper::uSummarySpend($post['member_id'],date('Y'),date('m'));
		$db = JFactory::getDbo();
		$sql = 'SELECT total,member_id FROM #__wrd_spending_summary WHERE member_id = '. $post['member_id'] .' ORDER BY year DESC,month DESC LIMIT 1';
		$db->setQuery($sql);
		$rs = $db->loadObject();
		$query = 'UPDATE #__wrd_profile SET total_spend = '.$rs->total.' WHERE member_id = '.$post['member_id'];
		$db->setQuery($query);
		$db->query();
		$dob = $post['year_birth']."-".$post['month_birth']."-".$post['day_birth'];
		WrdHelper::updatePointOfUser($post['user_id'],$post['member_id'],$dob,$post['f_name'],$post['l_name']);
		$this->setRedirect('index.php?option=com_wrd&controller=profile&id='.$post['id'].'&layout=form&tab=transaction','Finish update transaction');
	}
    function remove()
	{
		// Check for request forgeries
		JRequest::checkToken() or jexit( 'Invalid Token' );
		
		$cid = JRequest::getVar( 'cid', array(), 'post', 'array' );
		JArrayHelper::toInteger($cid);
		
		if (count( $cid ) < 1) {
		
			JError::raiseError(500, JText::_( 'Select an item to delete' ) );
		}
		
		$model = $this->getModel('profile');
		if(!$model->delete($cid)) {
			echo "<script> alert('".$model->getError(true)."'); window.history.go(-1); </script>\n";
		}
		
		$this->setRedirect( 'index.php?option='.$this->option.'&controller='.$this->controller,'Removed');
	}
   
    function publish()
	{
		// Check for request forgeries
		JRequest::checkToken() or jexit( 'Invalid Token' );
		$cid = JRequest::getVar( 'cid', array(), 'post', 'array' );
		JArrayHelper::toInteger($cid);
		if (count( $cid ) < 1) {
			JError::raiseError(500, JText::_( '<p style="color:red">Please select an item to publish</p>' ) );
		}
		$model = $this->getModel('profile');
		if(!$model->publish($cid, 1)) {
			echo "<script> alert('".$model->getError(true)."'); window.history.go(-1); </script>\n";
		}
		$this->setRedirect('index.php?option='.$this->option.'&controller='.$this->controller,'Published');
	}
	function unpublish(){
		
		// Check for request forgeries
		JRequest::checkToken() or jexit( 'Invalid Token' );
		$cid = JRequest::getVar( 'cid', array(), 'post', 'array' );
		JArrayHelper::toInteger($cid);
		if (count( $cid ) < 1) {
			JError::raiseError(500, JText::_( '<p style="color:red">Please select an item to publish</p>'  ) );
		}
		$model = $this->getModel('profile');
		
		if(!$model->publish($cid, 0)) {
			echo "<script> alert('".$model->getError(true)."'); window.history.go(-1); </script>\n";
		}
		
		$this->setRedirect('index.php?option='.$this->option.'&controller='.$this->controller,'Unpublished');
	}
	
	function cancel(){
		$post = JRequest::get('post');
		if(!empty($post['mid'])){
			$this->setRedirect('index.php?option=com_wrd&controller=profile&id='.$post['mid'].'&layout=form');
		}else{
			$this->setRedirect('index.php?option='.$this->option.'&controller='.$this->controller);
		}
	}
	
	//New items : points, complain, ...
	function newitem(){
       $app = JFactory::getApplication() ;
       $post = JRequest::get('post');
       if(isset($post['complain_flag'])){	
       		$app->setUserState('complain_flag', $post['complain_flag']) ;
       		$app->setUserState('user_id', $post['user_id']) ;
       		$app->redirect(JURI::base().'index.php?option=com_wrd&controller=complain&task=add') ;
       }else{
       		if(isset($post['flag_add_point'])){
	       		$app->setUserState('flag_add_point', $post['flag_add_point']) ;
	       		$app->setUserState('user_id', $post['user_id']) ;
	       		$app->redirect(JURI::base().'index.php?option=com_wrd&controller=profile&task=add_points') ;
       		}
       }
    }
    
	function export(){
		$mainframe = JFactory::getApplication();
		$db = JFactory::getDbo();
		$current = JRequest::getInt('current');
		$query = $mainframe->getUserState('com_wrd.profile.search');
		
		//if($total > 0){
		if(1){
			$query = $mainframe->getUserState('com_wrd.profile.search');
			$db->setQuery($query.' LIMIT '.$current.' ,20');
		}
		exit() ;
	}
    
    /*function printnewredemption() {
        JRequest::setVar( 'layout', 'addredemption'  );
        JRequest::setVar( 'view'  , 'profile');
        
        parent::display();    
    }*/
	
    public function savenewredemption()
    {
		JRequest::setVar( 'layout', 'addredemption');
		JRequest::setVar( 'view'  , 'profile');
        parent::display();    
    }
    
	public function save_sub_point(){
		$app = JFactory::getApplication() ;
		$user = JFactory::getUser() ;
		
		$post = JRequest::get('post') ;
	
		$model_point = $this->getModel('exchange');
		$user_profile = WrdHelper::getUserProfile($post['id'],'userid') ;
		$p_o_u = $model_point->getPointOfUser($post['id']) ;
		
		$r_point = $model_point->getRedemptionDetails($post['rid']) ;
		$t_tottal = 0 ;
		foreach ($p_o_u as $p_detail){
			if($post['p'.$p_detail->id] > $p_detail->point ){// if point of each transaction < point of user input
				$app->redirect('index.php?option=com_wrd&controller=profile&id='.$user_profile->id.'&layout=form','Error') ;
			}else{
				$total = $total + $post['p'.$p_detail->id] ;
			}
		}
		if($total > $r_point->point){// if total point user input > point of redemption
			$app->redirect('index.php?option=com_wrd&controller=profile&id='.$user_profile->id.'&layout=form','Error') ;
		}
		
		//If point of redemption > point_substrac ---> update redemption
		foreach ($p_o_u as $p_detail){
			if($post['p'.$p_detail->id] > 0){
				if($post['p'.$p_detail->id] < $p_detail->point ){
					$p_after = 	$p_detail->point - $post['p'.$p_detail->id] ;
					$rs = $model_point->UpdatePoint($p_detail->id, $p_after, $user->id , date("Y-m-d") ) ;
					if($rs == true){
						//add log point
						$model_point->logPoint($p_detail->id,$post['rid'], $post['p'.$p_detail->id], $user->id) ;
						if(!empty($r_point->point_id)){
                            //var_dump($r_point->point_id); die;  
							$model_point->DeletePoint($r_point->point_id) ;
						}
						//Approve for redemption
						$model_point->ApproveRedemption ($post['rid'], date("Y-m-d H:i:s")) ;
					}
				}else if($post['p'.$p_detail->id] == $p_detail->point ){
					$model_point->UpdatePoint($p_detail->id, 0, $user->id , date("Y-m-d")) ;
					if($rs == true){
						//add log point
						$model_point->logPoint($p_detail->id,$post['rid'], $post['p'.$p_detail->id], $user->id);
						if(!empty($r_point->point_id)){
							$model_point->DeletePoint($r_point->point_id) ;
						}
						//Approve for redemption
						$model_point->ApproveRedemption ($post['rid'], date("Y-m-d H:i:s")) ;
					}
				}
			}
		}
		$app->redirect('index.php?option=com_wrd&controller=profile&id='.$user_profile->id.'&layout=form') ;
	}
	//Dung cho backend approve gift from fondend
	public function approve(){
		
		$app = JFactory::getApplication() ;
		$db = JFactory::getDbo();
		$id = JRequest::getInt('id');
		//Update vip_wrd_redemption
		date_default_timezone_set('Asia/Ho_Chi_Minh'); 
		$user = JFactory::getUser();
		
		$user_profile = WrdHelper::getUserProfile($id,"id");
		
		//Kiem tra neu email contact cua member co thi send email template notification toi member don hang da duoc approve
		$message = "";
		if($user_profile->p_email){	
			
			$user_profile->code = JRequest::getVar('code');
			
			$order = WrdHelper::getRecordOfRedemptionByCode($user_profile->code);
			//echo "<pre>";print_r($order);exit;
			$user_profile->order_date = $order[0]->exchange_date;
			
			//$outlet = WrdHelper::getOutlet($order->requested_outlet);
			
			//$outletTranslate = WrdHelper::getOutletTranslate($order[0]->requested_outlet); 
			
			$outlet = WrdHelper::getOutlet($order[0]->requested_outlet);
			
			//echo "<pre>";var_dump($outlet);exit;
			
			if($user_profile->nationality == 249){
					
				$list_items = "<table width='100%' border='1'><tr><th>Thá»© tá»±</th><th>Sá»‘ lÆ°á»£ng</th><th>TÃªn mÃ³n quÃ </th><th>Ä�iá»ƒm</th><th>Tiá»�n</th></tr>";	
				$user_profile->requested_outlet =  $outlet->name_vi;
				$user_profile->requested_outlet_address = $outlet->address_vi;
			}
			else {
				$user_profile->requested_outlet =  $outlet->name;
				$user_profile->requested_outlet_address = $outlet->address;
				$list_items = "<table width='100%' border='1'><tr><th>Order</th><th>Quantity</th><th>Product Name</th><th>Point</th><th>Cash</th></tr>";
			}
			
			$count = 0;
			
			foreach ($order as $item){
			
				$count++;
				$product = WrdHelper::getProduct($item->product_id);
				$productName = unserialize($product->name);
				if($user_profile->nationality == 249){
				
					$productName = $productName['vi-VN'];
				}
				else {
				
					$productName = $productName['en-GB'];
				}
					
				$point_Of_Items = number_format( $item->point ,0,".",",");
					
				$cash = number_format($item->cash,0,".",",");
				
				$list_items .= "<tr><td>$count</td><td>$item->quantity</td><td>$productName</td><td>$point_Of_Items</td><td>$cash</td></tr>";
			
			}
			
			$list_items .= "</table>";
			
			$user_profile->list_items = $list_items;
			
			$resultSendEmailNotification = WrdHelper::sendEmailWhenAprroveOrder($user_profile);
			
			if($resultSendEmailNotification){
				
				$message = "You've just apporved a redemption. An email has been sent to VIP Member at '".$user_profile->p_email."' for notificating";
				
			}
			else {
				
				$message = "Email sent to  '".$user_profile->p_email."' failure";
			}
		}
		
		$date = date("Y-m-d H:i:s");
		$sql = "UPDATE #__wrd_redemption SET approved = 1,approved_date='".$date."',updated_by='".$user->id."',updated_date='".$date."' WHERE code = '".JRequest::getVar('code')."' ";
		$db->setQuery($sql);$db->query();
		
		//Update vip_wrd_redem_report_voucher
		$sql = "UPDATE #__wrd_redem_report_voucher SET approved = 1 WHERE code_redemption = '".JRequest::getVar('code')."' ";
		$db->setQuery($sql);$db->query();
		
		
		$app->redirect('index.php?option=com_wrd&controller=profile&id='.$id.'&layout=form&tab=redemption',$message) ;
		jexit();
	}
	public function n_approve(){
	
		$app = JFactory::getApplication() ;
		$user = JFactory::getUser() ;
		
		$model_point = $this->getModel('exchange');
		$model_profile = $this->getModel('profile');
		$user_profile = $model_profile->getItem(JRequest::getInt('id')) ;
		$r_point = $model_point->getRedemptionDetails(JRequest::getInt('rid')) ;
		
		if(!empty($r_point)){
			if(!empty($r_point->point_id)){
			
				$model_point->DeletePoint($r_point->point_id) ;
			}
			
			$model_point->NoneApproveRedemption (JRequest::getInt('rid') , date("Y-m-d H:i:s")) ;
			$model_point->ReverseProductQuantity($r_point->product_id, $r_point->quantity) ;
		}
		$app->redirect('index.php?option=com_wrd&controller=profile&id='.$user_profile->id.'&layout=form') ;
	}
	
	//revert redemtion point
	public function r_approve(){
		
		date_default_timezone_set('Asia/Ho_Chi_Minh');
		
		$app = JFactory::getApplication() ;
		$user = JFactory::getUser();
		$profile_id = JRequest::getInt('id');
		$db = JFactory::getDbo();
		$code = JRequest::getVar('code');
		if(empty($profile_id)){
			$app->redirect('index.php?option=com_wrd&controller=profile') ;
		}
		$profile = WrdHelper::getUserProfile($profile_id,$type='id');
		$q = "SELECT id FROM #__wrd_redemption WHERE code = '".$code."'";
		$db->setQuery($q);$rows = $db->loadObjectList();
		
		if(!empty($rows)) {
			foreach($rows as $row) {
			   
				$q = 'SELECT user_id,created_date FROM #__wrd_point WHERE redemption_id ="'.$code.'"';
				$db->setQuery($q);
				$rowsQ = $db->loadObjectList();
				
				//Delete record from point
				$sql = 'DELETE FROM #__wrd_point WHERE redemption_id ="'.$code.'"';
				$db->setQuery($sql);
				$db->query();
				
				foreach($rowsQ as $row):
					
					$year = date("Y",strtotime($row->created_date));
					$month = date('m',strtotime($row->created_date));
					if($year < date('Y')||(($year == date('Y'))&&($month <= date('m')))){
					
						while(($month != date('m'))||($year != date('Y'))){
							WrdHelper::updateSummaryPoint($row->user_id,$year,$month);
							if($month+1 <=12) ++$month;
							else {$month = 1;++$year;}
						}
						WrdHelper::updateSummaryPoint($row->user_id,date('Y'),date('m'));
					}
					
					$p_o_u = WrdHelper::getPoints($row->user_id);
					$sql = 'UPDATE #__wrd_profile SET p_o_u = '.$p_o_u->point.' ,point_life_time = '.$p_o_u->point_life_time.' WHERE user_id = '.$row->user_id;
					$db->setQuery($sql);
					$db->query();
				endforeach;
				/***** Set status *****/
				$sql = "UPDATE #__wrd_redemption SET approved = 9,updated_by = '".$user->id."',updated_date = '".date("Y-m-d H:i:s")."' WHERE code = '".$code."' ";
				
				$db->setQuery($sql);$db->query();
				
				//Update vip_wrd_redem_report_voucher
				$sql = "UPDATE #__wrd_redem_report_voucher SET status = 9 WHERE code_redemption = '".$code."'";
				$db->setQuery($sql);$db->query();
				
				/***** Update Product quantity *****/
				$currentRedemption = "
					SELECT
						`t`.id,
						`t`.quantity,
						`t`.product_id
					FROM #__wrd_redemption `t`
					WHERE `t`.id = ".intval($row->id)."
				"; 
				$db->setQuery($currentRedemption);
				$currentRedemption = $db->loadObject();
				if(!empty($currentRedemption)) {
					$sql = "
						UPDATE #__wrd_products
						SET quantity = quantity + ".intval($currentRedemption->quantity)."
						WHERE id = ".intval($currentRedemption->product_id)."
					";
					$db->setQuery($sql);
					$db->query();  
				}
				/***** Delete Log *****/
				$query = 'DELETE FROM #__wrd_lpointredemtion WHERE rid= '.$row->id;
				$db->setQuery($query);
				$db->query();
			}
		}
        
		WrdHelper::updatePointOfUser($profile->user_id,$profile->member_id,$profile->dob,$profile->f_name,$profile->l_name);
		
		$app->redirect('index.php?option=com_wrd&controller=profile&id='.$profile_id.'&layout=form&tab=redemption') ;
	}
	public function view_activity(){
		$app = JFactory::getApplication() ;
		$post = JRequest::get('post') ;
		$month 	= empty($post['month']) ? 0 : $post['month'] ; 
		$year   = empty($post['year']) ? 0 : $post['year'] ;
		
		$link = 'index.php?option=com_wrd&view=profile&controller=profile&id='.$post['id'].'&layout=form' ;
		if(!empty($month)){
			$link .= '&month='.$month ; 
		}
		if(!empty($year)){
			$link .= '&year='.$year ;
		}
		
		$app->redirect($link);
	}
	
	public function save_redemption_details(){
		exit();
		$db = JFactory::getDbo();
		$app = JFactory::getApplication() ;
		$post = JRequest::get('post') ;
		$user_id = $post['user_id'] ;
		unset($post['user_id']) ;
		unset($post['product_id']) ;
		unset($post['exchange_date']) ;
		unset($post['approved']) ;
		unset($post['approved_date']) ;
		unset($post['code']) ;
		unset($post['point']) ;
		unset($post['cash']) ;
		unset($post['point_id']) ;
		
		$query = '
			UPDATE #__wrd_redemption 
			SET `status_of_redemption` ='.$post['status_of_redemption'].' ,
			 `status_of_redemption_date` = "'.date('Y-m-d').'",
			 `pick_up_date` = "'.$post['pick_up_date'].'" ,
			 `pick_up_at` = "'.$post['pick_up_at'].'" ,
			 `phone_num` = "'.$post['phone_num'].'" 
			 WHERE id ='.$post['id'] ;
		$db->setQuery($query);
		$rs = $db->query();
		if($rs == true){
			$user_info = WrdHelper::getUserProfile($user_id,'userid') ;
			$app->redirect('index.php?option=com_wrd&controller=profile&id='.$user_info->id.'&layout=form','Saved') ;
		}else{
			$app->redirect('index.php?option=com_wrd&controller=profile&layout=rdetails&id='.$post['id'],'Error Save') ;
		}
	}
	
	function save_new_redemption(){
		exit();
		$db = JFactory::getDbo();
		$app = JFactory::getApplication() ;
		$post = JRequest::get('post');
		$post['quantity'] = empty($post['quantity']) ? 1 : $post['quantity'] ;
		$c_user = JFactory::getUser() ;
		$user_info = WrdHelper::getUserProfile($post['uid'] , 'userid') ;
        
        /***** Get chooser product *****/
		$model_product = &JModelLegacy::getInstance('products','WrdModel');
		$product = $model_product->getItem($post['product_id']) ;
		
        /***** Compare quantity *****/
        if($post['quantity'] > $product->quantity){
			$app->redirect('index.php?option=com_wrd&controller=profile&id='.$user_info->id.'&layout=form&tab=redemption','Have no product');
			return false;
		}
		
		$vercode = $this->random_letters() ;
		$point = WrdHelper::getPoints($post['uid']);  // Lay so diem ma user co duoc
		if($post['type_redeem'] == '1'){
			$t_point = ($product->point * $post['quantity'] ) ;
			$t_cash = 0 ;
			$point_redeem = ( $product->point * $post['quantity'] ) ;
		}else{
			$t_point = ( $product->pointx * $post['quantity'] ) ;
			$t_cash = ( $product->cash * $post['quantity'] ) ;
			$point_redeem = ($product->pointx * $post['quantity'] ) ;
		}
		
		if($point >= $point_redeem){
			
			//updated point
			$obj = new stdClass();
			$obj->id = null;
			$obj->user_id = $post['uid'] ;
			$obj->transaction = $product->id ;
			$obj->type = 0 ;
			$obj->point = -$point_redeem ;
			$obj->expire = '0000-00-00 00:00:00' ;
			$obj->point = -$point_redeem;
			$obj->des = 'Redemption';
			$obj->created_id = $c_user->id ;
			$obj->created_date = date('Y-m-d') ;
			$obj->modify_id = '';
			$obj->modify_date = '';
			
			$db->insertObject('#__wrd_point', $obj);
			
			WrdHelper::updateSummaryPoint($obj->user_id,date('Y'),date('m'));
			$p_o_u = WrdHelper::getPoints($obj->user_id);
			$sql = 'UPDATE #__wrd_profile SET p_o_u = '.$p_o_u->point.' ,point_life_time = '.$p_o_u->point_life_time.' WHERE user_id = '.$obj->user_id;
			$db->setQuery($sql);
			$db->query();
			
			$profile =  WrdHelper::getUserProfile($obj->user_id,'userid');
			WrdHelper::updatePointOfUser($obj->user_id,$profile->member_id,$profile->dob,$profile->f_name,$profile->l_name);
			
			unset($obj);
			$temp = $db->insertid() ;
			//process gift
			$obj = new stdClass();
			$obj->id = null;
			$obj->user_id = $post['uid'] ;
			$obj->created_id = $c_user->id ;
			$obj->product_id = $product->id ;
			$obj->exchange_date = date("Y-m-d H:i:s") ;
			$obj->approved_date = '0000-00-00 00:00:00' ;
			$obj->approved = 0 ;
			$obj->code = $vercode ;
			$obj->point = $t_point ;
			$obj->cash = $t_cash ;
			$obj->point_id = $temp ;
			$obj->status_of_redemption = 1 ;
			$obj->status_of_redemption_date = date("Y-m-d H:i:s") ;
			$obj->pick_up_date = '0000-00-00 00:00:00' ;
			$obj->phone_num = '' ;
			$obj->quantity = $post['quantity'] ;
			$db->insertObject('#__wrd_redemption', $obj) ;
			
			//update quality
			$query = 'UPDATE #__wrd_products SET quantity = '.($product->quantity - $post['quantity']).' WHERE id = '.$product->id;
			$db->setQuery($query);
			$db->query();
			
			//send mail
			$app->redirect('index.php?option=com_wrd&controller=profile&id='.$user_info->id.'&layout=form&tab=redemption','Saved') ;
			return false;
		}else{
			$app->redirect('index.php?option=com_wrd&controller=profile&id='.$user_info->id.'&layout=form&tab=redemption','Need more point');
			return false;
		}				
    }
    
    function redirect_to_profile() {
    	$app = JFactory::getApplication() ;
		$post = JRequest::get('post');
		$post['uid'] = empty($post['uid']) ? $post['user_id'] : $post['uid'] ;
		$user_info = WrdHelper::getUserProfile($post['uid'] , 'userid') ;
		$app->redirect('index.php?option=com_wrd&controller=profile&id='.$user_info->id.'&layout=form');
    }
    
	function products_page() {
    	$app = JFactory::getApplication() ;
		$app->redirect('index.php?option=com_wrd&controller=products');
    }
    
	function random_letters(){
	 
	 	$vercode = WrdHelper::random_letters();
    	return $vercode ;
	}
	function isEmail($email)
	{
		return (preg_match("/[-a-zA-Z0-9_.+]+@[a-zA-Z0-9-]{2,}\.[a-zA-Z]{2,}/", $email) > 0) ? true : false;
	}
	
	
	function send_mail_renew()
	{
		// Check for request forgeries
		JRequest::checkToken() or jexit( 'Invalid Token' );
		$cid = JRequest::getVar( 'cid', array(), 'post', 'array' );
		JArrayHelper::toInteger($cid);
		if (count( $cid ) < 1) {
			JError::raiseError(500, JText::_( '<p style="color:red">Please select an item to send email</p>' ) );
		}
		
		$model = $this->getModel('profile');
		$model->send_email($cid, 'send_mail_renew') ;
		$this->setRedirect('index.php?option='.$this->option.'&controller='.$this->controller,'Sent');
	}
	
	function send_mail_verify()
	{
		// Check for request forgeries
		JRequest::checkToken() or jexit( 'Invalid Token' );
		$cid = JRequest::getVar( 'cid', array(), 'post', 'array' );
		JArrayHelper::toInteger($cid);
		if (count( $cid ) < 1) {
			JError::raiseError(500, JText::_( '<p style="color:red">Please select an item to send email</p>' ) );
		}
		
		$model = $this->getModel('profile');
		$model->send_email($cid, 'send_mail_verify') ;
		$this->setRedirect('index.php?option='.$this->option.'&controller='.$this->controller,'Sent');
	}
	
	function send_mail_birth()
	{
		// Check for request forgeries
		JRequest::checkToken() or jexit( 'Invalid Token' );
		$cid = JRequest::getVar( 'cid', array(), 'post', 'array' );
		JArrayHelper::toInteger($cid);
		if (count( $cid ) < 1) {
			JError::raiseError(500, JText::_( '<p style="color:red">Please select an item to send email</p>' ) );
		}
		//echo "<pre>";print_r($cid);exit;
		$model = $this->getModel('profile');
		$model->send_email($cid, 'send_mail_birth') ;
		$this->setRedirect('index.php?option='.$this->option.'&controller='.$this->controller,'Sent');
	}
	
	function send_pickup_notice()
	{
		// Check for request forgeries
		JRequest::checkToken() or jexit( 'Invalid Token' );
		$cid = JRequest::getVar( 'cid', array(), 'post', 'array' );
		JArrayHelper::toInteger($cid);
		if (count( $cid ) < 1) {
			JError::raiseError(500, JText::_( '<p style="color:red">Please select an item to send email</p>' ) );
		}
		
		$model = $this->getModel('profile');
		$model->send_email($cid, 'send_pickup_notice') ;
		$this->setRedirect('index.php?option='.$this->option.'&controller='.$this->controller,'Sent');
	}
	
	function reApplyVipCard(){
		$id = JRequest::getInt('user_id');
		$db = JFactory::getDbo();
		$reapply_date = date('Y-m-d H:i:s');
		
		$query = 'UPDATE #__wrd_profile SET reapply_date = "'.$reapply_date.'", `status_of_card` = 1, `non_pick_up_date` = "", `pick_up_date` = "", `pick_up_at` = "", `non_pick_up_at` = "", `mem_card_outlet` = "" WHERE user_id = '.$id;
		$db->setQuery($query)->query();
		echo $reapply_date;
		jexit();
	}
	
	function check_expired_point(){
		$db = &JFactory::getDbo();
		$query = 'SELECT * FROM `#__wrd_point` WHERE expire != "0000-00-00" AND expired = 0';
		$rs = $db->setQuery($query)->loadObjectList();
		
		foreach ($rs as $item){
			if(strtotime($item->expire.' 23:59:59') < time()){
				$point_obj = new stdClass();
				$point_obj->id = $item->id;
				$point_obj->expired = 1;
				$db->updateObject('#__wrd_point', $point_obj, 'id');
			}
		}
		
		$query = 'SELECT * FROM `#__wrd_point` WHERE expired = 1 AND type != 9';
		$expired_rs = $db->setQuery($query)->loadObjectList();
		
		foreach ($expired_rs as $expired){
			$query = 'SELECT * FROM `#__wrd_point` 
					WHERE expired = 0 AND 
							type = 9 AND 
							user_id = '.$expired->user_id.' AND 
							transaction = "'.$expired->transaction.'"';
			
			$rs1 = $db->setQuery($query)->loadObjectList();
			
			foreach ($rs1 as $row){
				$point_obj = new stdClass();
				$point_obj->id = $row->id;
				$point_obj->expired = 1;
				$db->updateObject('#__wrd_point', $point_obj, 'id');
			}
		}
		
		$this->setRedirect('index.php?option='.$this->option.'&controller='.$this->controller,'Checked...');
	}
	
	function mergeProfile(){
		
		$app = &JFactory::getApplication();
		$db = &JFactory::getDbo();
		$user = &JFactory::getUser();
		$emailBody = '<p><b>User Name:</b>'.$user->name.'</p>';
		
		$post = JRequest::get('post');
		$backup = new stdClass();
		$backup->id = null;
		$backup->member_id = null;
		$backup->merge_member_id = $post['member_id'];
		$backup->data_type = null;
		$backup->data = null;
		$backup->created_by = $user->id;
		$backup->created_time = date($db->getDateFormat(),time());
		
		if($post['merge_memberid'] == '')
			$app->redirect('index.php?option=com_wrd&controller=profile&layout=form&id='.$post['id'],'Empty member id','error');
		
		//check member id is valid
		$old_member = WrdHelper::getUserProfile($post['merge_memberid'],'member_id');
		if(intval($old_member->user_id) == 0)
			$app->redirect('index.php?option=com_wrd&controller=profile&layout=form&id='.$post['id'],'Empty member id','error');
		
		$emailBody .= '<p><b>Member Id:</b>'.$post['member_id'].'/'.$post['merge_memberid'].'</p>';
		$emailBody .= '<p><b>Member Name:</b>'.$post['f_name'].' '.$post['l_name'].'/'.$old_member->f_name.' '.$old_member->l_name.'</p>';
		$emailBody .= '<p><b>Member Phone:</b>'.$post['phone'].'/'.$old_member->phone.'</p>';
		$emailBody .= '<p><b>Member Email:</b>'.$post['p_email'].'/'.$old_member->p_email.'</p>';
		
		$backup->member_id = $old_member->member_id;
		
		//transaction
		$transaction_query = 'SELECT * FROM #__wrd_transaction WHERE vip_number = '.$old_member->member_id ;
		$transaction_rs = $db->setQuery($transaction_query)->loadObjectList();
		$uni_id = uniqid('transaction:');
		if (count($transaction_rs) > 0){
			foreach ($transaction_rs as $transaction_item)
			{
				$backup->data = serialize($transaction_item);
				$backup->data_type = $uni_id;
				
				$db->insertObject('#__wrd_mergebackup', $backup);
			}
		}
		
		$transaction_query = 'UPDATE #__wrd_transaction SET vip_number='.$post['member_id'].' WHERE vip_number = '.$old_member->member_id ;
		$db->setQuery($transaction_query)->query();

		//point
		$point_query = 'SELECT * FROM `#__wrd_point` WHERE user_id = '.$old_member->user_id ;
		$uni_id = uniqid('point:');
		$point_rs = $db->setQuery($point_query)->loadObjectList();
		
		if (count($point_rs) > 0){
			foreach ($point_rs as $point_item)
			{
				$backup->data = serialize($point_item);
				$backup->data_type = $uni_id;
		
				$db->insertObject('#__wrd_mergebackup', $backup);
			}
		}
		
		$point_query = 'UPDATE #__wrd_point SET user_id ='.$post['user_id'].' WHERE user_id = '.$old_member->user_id ;
		$db->setQuery($point_query)->query();
		
		//pointsumary
		$pointsumary_query = 'SELECT * FROM `#__wrd_points_summary` WHERE user_id = '.$old_member->user_id ;
		//file_put_contents('logmergequery.txt', print_r($pointsumary_query,1),FILE_APPEND);
		$uni_id = uniqid('pointsumary:');
		$pointsumary_rs = $db->setQuery($pointsumary_query)->loadObjectList();
		
		if (count($pointsumary_rs) > 0){
			foreach ($pointsumary_rs as $pointsumary_item)
			{
				$backup->data = serialize($pointsumary_item);
				$backup->data_type = $uni_id;
		
				$db->insertObject('#__wrd_mergebackup', $backup);
			}
		}
		
		$pointsumary_query = 'UPDATE #__wrd_points_summary SET user_id ='.$post['user_id'].' WHERE user_id = '.$old_member->user_id ;
		//file_put_contents('logmergequery.txt', print_r($pointsumary_query,1),FILE_APPEND);
		
		$pointsumary_query = 'DELETE #__wrd_points_summary WHERE user_id = '.$post['user_id'] ;
		//file_put_contents('logmergequery.txt', print_r($pointsumary_query,1),FILE_APPEND);		
		$db->setQuery($pointsumary_query)->query();
		
		//spendingsumary
		$spendingsumary_query = 'SELECT * FROM `#__wrd_spending_summary` WHERE user_id = '.$old_member->user_id ;
		//file_put_contents('logmergequery.txt', print_r($spendingsumary_query,1),FILE_APPEND);
		$uni_id = uniqid('spendingsumary:');
		$spendingsumary_rs = $db->setQuery($spendingsumary_query)->loadObjectList();
		
		if (count($spendingsumary_rs) > 0){
			foreach ($spendingsumary_rs as $spendingsumary_item)
			{
				$backup->data = serialize($spendingsumary_item);
				$backup->data_type = $uni_id;
		
				$db->insertObject('#__wrd_mergebackup', $backup);
			}
		}
		
		$spendingsumary_query = 'UPDATE #__wrd_spending_summary SET user_id ='.$post['user_id'].' WHERE user_id = '.$old_member->user_id ;
		//file_put_contents('logmergequery.txt', print_r($spendingsumary_query,1),FILE_APPEND);
		$spendingsumary_query = 'DELETE #__wrd_spending_summary WHERE user_id = '.$post['user_id'] ;
		//file_put_contents('logmergequery.txt', print_r($spendingsumary_query,1),FILE_APPEND);
		$db->setQuery($spendingsumary_query)->query();
		
		//memberservice
		$mservices_query = 'SELECT * FROM #__wrd_mservices WHERE vip_number = '.$old_member->member_id ;
		//file_put_contents('logmergequery.txt', print_r($mservices_query,1),FILE_APPEND);
		$mservices_rs = $db->setQuery($mservices_query)->loadObjectList();
		$uni_id = uniqid('mservices:');
		if (count($mservices_rs) > 0){
			foreach ($mservices_rs as $mservices_item)
			{
				$backup->data = serialize($mservices_item);
				$backup->data_type = $uni_id;
				
				$db->insertObject('#__wrd_mergebackup', $backup);
			}
		}
		
		$mservices_query = 'UPDATE #__wrd_mservices SET vip_number='.$post['member_id'].' WHERE vip_number = '.$old_member->member_id ;
		//file_put_contents('logmergequery.txt', print_r($mservices_query,1),FILE_APPEND);
		$db->setQuery($mservices_query)->query();	
		
		//complain
		$complain_query = 'SELECT * FROM #__wrd_complain WHERE vip_number = '.$old_member->member_id ;
		//file_put_contents('logmergequery.txt', print_r($complain_query,1),FILE_APPEND);
		$complain_rs = $db->setQuery($complain_query)->loadObjectList();
		$uni_id = uniqid('complain:');
		if (count($complain_rs) > 0){
			foreach ($complain_rs as $complain_item)
			{
				$backup->data = serialize($complain_item);
				$backup->data_type = $uni_id;
		
				$db->insertObject('#__wrd_mergebackup', $backup);
			}
		}
		
		$complain_query = 'UPDATE #__wrd_complain SET vip_number='.$post['member_id'].' WHERE vip_number = '.$old_member->member_id ;
		//file_put_contents('logmergequery.txt', print_r($complain_query,1),FILE_APPEND);
		$db->setQuery($complain_query)->query();
		
		
		//redemption
		$redemption_query = 'SELECT * FROM `#__wrd_redemption` WHERE user_id = '.$old_member->user_id ;
		//file_put_contents('logmergequery.txt', print_r($redemption_query,1),FILE_APPEND);
		$uni_id = uniqid('redemption:');
		$redemption_rs = $db->setQuery($redemption_query)->loadObjectList();
		
		if (count($redemption_rs) > 0){
			foreach ($redemption_rs as $redemption_item)
			{
				$backup->data = serialize($redemption_item);
				$backup->data_type = $uni_id;
		
				$db->insertObject('#__wrd_mergebackup', $backup);
			}
		}
		
		$redemption_query = 'UPDATE #__wrd_redemption SET user_id ='.$post['user_id'].' WHERE user_id = '.$old_member->user_id ;
		//file_put_contents('logmergequery.txt', print_r($redemption_query,1),FILE_APPEND);
		$db->setQuery($redemption_query)->query();
		
		//discount_profile __wrd_discount_profile
		$discount_profile_query = 'SELECT * FROM #__wrd_discount_profile WHERE vip_number = '.$old_member->member_id ;
		//file_put_contents('logmergequery.txt', print_r($discount_profile_query,1),FILE_APPEND);
		$discount_profile_rs = $db->setQuery($discount_profile_query)->loadObjectList();
		$uni_id = uniqid('discount_profile:');
		if (count($discount_profile_rs) > 0){
			foreach ($discount_profile_rs as $discount_profile_item)
			{
				$backup->data = serialize($discount_profile_item);
				$backup->data_type = $uni_id;
		
				$db->insertObject('#__wrd_mergebackup', $backup);
			}
		}
		
		$discount_profile_query = 'DELETE FROM #__wrd_discount_profile WHERE vip_number = '.$old_member->member_id ;
		//file_put_contents('logmergequery.txt', print_r($discount_profile_query,1),FILE_APPEND);
		$db->setQuery($discount_profile_query)->query();
		
		//user __wrd_users
		$user_query = 'SELECT * FROM #__users WHERE id = '.$old_member->user_id ;
		//file_put_contents('logmergequery.txt', print_r($user_query,1),FILE_APPEND);
		$user_rs = $db->setQuery($user_query)->loadObject();
		$uni_id = uniqid('user:');
		
		$backup->data = serialize($user_rs);
		$backup->data_type = $uni_id;
		$db->insertObject('#__wrd_mergebackup', $backup);
		
		$user_query = 'DELETE FROM #__users WHERE id = '.$old_member->user_id ;
		//file_put_contents('logmergequery.txt', print_r($user_query,1),FILE_APPEND);
		$db->setQuery($user_query)->query();
		$user_query = 'DELETE FROM #__user_usergroup_map WHERE user_id = '.$old_member->user_id ;
		//file_put_contents('logmergequery.txt', print_r($user_query,1),FILE_APPEND);
		$db->setQuery($user_query)->query();
		
		//user_logregister  vip_wrd_log_register
		$logregister_query = 'SELECT * FROM #__wrd_log_register WHERE id = '.$old_member->user_id ;
		//file_put_contents('logmergequery.txt', print_r($logregister_query,1),FILE_APPEND);
		$logregister_rs = $db->setQuery($logregister_query)->loadObject();
		$uni_id = uniqid('logregistration:');
		if (count($logregister_rs) > 0){
			foreach ($logregister_rs as $logregister_item)
			{
				$backup->data = serialize($logregister_item);
				$backup->data_type = $uni_id;
				$db->insertObject('#__wrd_mergebackup', $backup);
			}
		}
		$logregister_query = 'UPDATE #__wrd_log_register SET id ='.$post['user_id'].' WHERE id = '.$old_member->user_id ;
		//file_put_contents('logmergequery.txt', print_r($logregister_query,1),FILE_APPEND);
		$db->setQuery($logregister_query)->query();
		
		//profile_old
		$uni_id = uniqid('user_old:');
		$backup->data = serialize($old_member);
		$backup->data_type = $uni_id;
		$db->insertObject('#__wrd_mergebackup', $backup);
		
		//profile_new
		$uni_id = uniqid('user_new:');
		$backup->data = serialize($post);
		$backup->data_type = $uni_id;
		$db->insertObject('#__wrd_mergebackup', $backup);
		$profile_query = 'DELETE FROM #__wrd_profile WHERE user_id = '.$post['user_id'];
		//file_put_contents('logmergequery.txt', print_r($profile_query,1),FILE_APPEND);
		$db->setQuery($profile_query)->query();
		
		$profile_query = 'UPDATE #__wrd_profile SET id ='.$post['user_id'].',member_id = '.$post['member_id'].' WHERE id = '.$old_member->user_id ;
		//file_put_contents('logmergequery.txt', print_r($profile_query,1),FILE_APPEND);
		$db->setQuery($profile_query)->query();

		//megetable
		$mobj = new stdClass();
		$mobj->member_id		=	$post['member_id'];
		$mobj->merge_member_id	=	$old_member->member_id;
		$db->insertObject('#__wrd_mergeid', $mobj);
		
		$old_member->user_id  	= $post['user_id'];
		$old_member->member_id  = $post['member_id'];
		
		$db->updateObject('#__wrd_profile', $old_member, 'id');
		
		WrdHelper::uSpend($old_member);
		WrdHelper::uPoint($old_member);
		
		//send email notice
		$emailSubject =  'WMCVIP - Merge profile - System report';
		$email	= array('dinh.chau@wmcvietnam.com','truongnhan0311@gmail.com' );
		$mailFrom = 'WMCVIP';
		JUtility::sendMail($mailFrom, 'WMCVIP', $email, $emailSubject, $emailBody,1);
		
		$app->redirect('index.php?option=com_wrd&controller=profile&layout=form&id='.$old_member->id,'Merge done');
	}
	
	function previewProflile(){
		$member_id = JRequest::getVar('mid');
		$old_member = WrdHelper::getUserProfile($member_id,'member_id');
		echo json_encode($old_member);
		jexit();
	}
}